package com.zxl.yjb.activity.home.order;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.zxl.yjb.R;
import com.zxl.yjb.adapter.MyFragmentPagerAdapter;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.ReadStatusBean;
import com.zxl.yjb.fragment.home.order.send.OrderSend_DJD_Fragment;
import com.zxl.yjb.fragment.home.order.send.OrderSend_FWZ_Fragment;
import com.zxl.yjb.fragment.home.order.send.OrderSend_SXD_Fragment;
import com.zxl.yjb.fragment.home.order.send.OrderSend_YWG_Fragment;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.widget.NoScrollViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;

public class OrderSendActivity extends BaseActivity implements IUnReadMessageObserver {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.tab_order)
    TabLayout tab_order;
    @BindView(R.id.vp_order)
    NoScrollViewPager vp_order;
    @BindView(R.id.tv_msg_num)
    TextView tvMsgNum;

    private MyFragmentPagerAdapter myFragmentPagerAdapter;

    private OrderSend_DJD_Fragment orderSend_djd_fragment;
    private OrderSend_FWZ_Fragment orderSend_fwz_fragment;
    private OrderSend_SXD_Fragment orderSend_sxd_fragment;
    private OrderSend_YWG_Fragment orderSend_ywg_fragment;

    private ArrayList<Fragment> fragmentList = new ArrayList<>();

    private String[] title = {"待接单","服务中","已完工","失效单"};
    private View[] tabView = new View[4];

    private DataManager dataManager;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        //注册融云im，未读消息的接受
        final Conversation.ConversationType[] conversationTypes = {
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP, Conversation.ConversationType.SYSTEM,
                Conversation.ConversationType.PUBLIC_SERVICE, Conversation.ConversationType.APP_PUBLIC_SERVICE
        };

        RongIM.getInstance().addUnReadMessageCountChangedObserver(this, conversationTypes);
    }

    @Override
    protected void initView() {
        tv_page_title.setText("已发订单");
        initFragment();
        initTab();
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    public void openList() {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put(Conversation.ConversationType.PRIVATE.getName(), false); //设置私聊会话是否聚合显示
        map.put(Conversation.ConversationType.GROUP.getName(), false);//群组
        map.put(Conversation.ConversationType.PUBLIC_SERVICE.getName(), false);//公共服务号
        map.put(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(),false);//订阅号
        map.put(Conversation.ConversationType.SYSTEM.getName(), false);//系统
        map.put(Conversation.ConversationType.DISCUSSION.getName(), false);
        RongIM.getInstance().startConversationList(OrderSendActivity.this,map);
    }

    private void initTab()
    {
        tab_order.setupWithViewPager(vp_order);
        for (int i = 0; i < title.length; i++) {
            tabView[i] = LayoutInflater.from(OrderSendActivity.this).inflate(R.layout.item_tab_order,null);
            ((TextView)tabView[i].findViewById(R.id.tv_tab_name)).setText(title[i]);
            tab_order.getTabAt(i).setCustomView(tabView[i]);
        }

        tab_order.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ((TextView)tabView[tab.getPosition()].findViewById(R.id.tv_tab_name)).setTextColor(getResources().getColor(R.color.main_color));
                tabView[tab.getPosition()].findViewById(R.id.view_line).setVisibility(View.VISIBLE);
                vp_order.setCurrentItem(tab.getPosition(),false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ((TextView)tabView[tab.getPosition()].findViewById(R.id.tv_tab_name)).setTextColor(getResources().getColor(R.color.black_color));
                tabView[tab.getPosition()].findViewById(R.id.view_line).setVisibility(View.GONE);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        ((TextView)tabView[0].findViewById(R.id.tv_tab_name)).setTextColor(getResources().getColor(R.color.main_color));
        tabView[0].findViewById(R.id.view_line).setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.iv_shopping_message,R.id.rl_msg_num})
    public void onClick(View v)
    {
        switch (v.getId()) {
            case R.id.iv_shopping_message:
                openList();//打开聊天列表
                break;
            case R.id.rl_msg_num:
                openList();//打开聊天列表
                break;

        	default:
        		break;
        }

    }

    private void initFragment()
    {
        orderSend_djd_fragment = new OrderSend_DJD_Fragment();
        orderSend_fwz_fragment = new OrderSend_FWZ_Fragment();
        orderSend_sxd_fragment = new OrderSend_SXD_Fragment();
        orderSend_ywg_fragment = new OrderSend_YWG_Fragment();
        fragmentList.add(orderSend_djd_fragment);
        fragmentList.add(orderSend_fwz_fragment);
        fragmentList.add(orderSend_ywg_fragment);
        fragmentList.add(orderSend_sxd_fragment);
        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);
        vp_order.setOffscreenPageLimit(3);
        vp_order.setAdapter(myFragmentPagerAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getReadState_DJD();
        getReadState_FWZ();
        getReadState_YWG();
        getReadState_SXD();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent)
    {
        switch (messageEvent.getMessage()) {
            case "paySuccess":
                getReadState_DJD();
                getReadState_FWZ();
//                getReadState_YWG();
//                getReadState_SXD();
                orderSend_djd_fragment.getData();
                orderSend_fwz_fragment.getData();
//                orderSend_sxd_fragment.getData();
//                orderSend_ywg_fragment.getData();
                vp_order.setCurrentItem(1);//支付成功跳到服务中
                break;
        }
    }


    private void getReadState_DJD()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("order_status","0");
        map.put("pay_status","0");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (tabView.length!=0&&tabView[0]!=null)
                {
                    if (readStatusBean.getHaveRead()==1)
                    {
                        tabView[0].findViewById(R.id.iv_isread).setVisibility(View.VISIBLE);
                    }
                    else if (readStatusBean.getHaveRead()==0)
                    {
                        tabView[0].findViewById(R.id.iv_isread).setVisibility(View.GONE);
                    }
                }

            }
        };
        dataManager.orderlist_request_read_get_status(new ProgressObserver<ReadStatusBean>(listener,OrderSendActivity.this),map);
    }

    private void getReadState_FWZ()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("order_status","1");
        map.put("pay_status","1");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (tabView.length!=0&&tabView[1]!=null)
                {
                    if (readStatusBean.getHaveRead()==1)
                    {
                        tabView[1].findViewById(R.id.iv_isread).setVisibility(View.VISIBLE);
                    }
                    else if (readStatusBean.getHaveRead()==0)
                    {
                        tabView[1].findViewById(R.id.iv_isread).setVisibility(View.GONE);
                    }
                }
            }
        };
        dataManager.orderlist_request_read_get_status(new ProgressObserver<ReadStatusBean>(listener,OrderSendActivity.this),map);
    }

    private void getReadState_YWG()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("order_status","2");
        map.put("pay_status","1");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (tabView.length!=0&&tabView[2]!=null)
                {
                    if (readStatusBean.getHaveRead()==1)
                    {
                        tabView[2].findViewById(R.id.iv_isread).setVisibility(View.VISIBLE);
                    }
                    else if (readStatusBean.getHaveRead()==0)
                    {
                        tabView[2].findViewById(R.id.iv_isread).setVisibility(View.GONE);
                    }
                }
            }
        };
        dataManager.orderlist_request_read_get_status(new ProgressObserver<ReadStatusBean>(listener,OrderSendActivity.this),map);
    }
    private void getReadState_SXD()
    {
        dataManager = new DataManager();
        Map<String ,String> map = new HashMap<>();
        map.put("order_status","3");
        map.put("pay_status","1");
        ObserverOnNextListener<ReadStatusBean> listener = new ObserverOnNextListener<ReadStatusBean>() {
            @Override
            public void onNext(ReadStatusBean readStatusBean) {
                if (tabView.length!=0&&tabView[3]!=null)
                {
                    if (readStatusBean.getHaveRead()==1)
                    {
                        tabView[3].findViewById(R.id.iv_isread).setVisibility(View.VISIBLE);
                    }
                    else if (readStatusBean.getHaveRead()==0)
                    {
                        tabView[3].findViewById(R.id.iv_isread).setVisibility(View.GONE);
                    }
                }
            }
        };
        dataManager.orderlist_request_read_get_status(new ProgressObserver<ReadStatusBean>(listener,OrderSendActivity.this),map);
    }

    @Override
    public void onCountChanged(int count) {
        if (count == 0) {
            tvMsgNum.setVisibility(View.GONE);
        } else if (count > 0 && count < 100) {
            tvMsgNum.setVisibility(View.VISIBLE);
            tvMsgNum.setText(String.valueOf(count));
        } else {
            tvMsgNum.setVisibility(View.VISIBLE);
            tvMsgNum.setText(R.string.no_read_message);
        }
    }
}
